import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/utils/file_utils.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:pdf/pdf.dart';
import 'package:printing/printing.dart';
import 'package:share/share.dart';

class PdfWatchView extends StatefulWidget {
  final String type;
  final int id;

  const PdfWatchView({Key key, this.type, this.id}) : super(key: key);

  @override
  PdfWatchViewState createState() => PdfWatchViewState();
}

class PdfWatchViewState extends State<PdfWatchView> {
  int count = 0;
  int total = 100;
  CancelToken cancelToken = CancelToken();

  Uint8List _uint8list;
  File pdfFile;

  @override
  void initState() {
    super.initState();
    loadingPDF();
  }

  @override
  void dispose() {
    super.dispose();
    cancelToken?.cancel();
  }

  void onShare() {
    if (pdfFile != null) {
      FileUtils.openFile(pdfFile);
    }
  }

  void loadingPDF() async {
    if (widget.type == null || widget.id == null) return;
    pdfFile = await FileUtils.getPdfFile(widget.type, widget.id,
        cancelToken: cancelToken, onReceiverProgress: (int count, int total) {
      setState(() {
        this.count = count;
        this.total = total;
      });
    });
    if (pdfFile != null) {
      setState(() {
        _uint8list = pdfFile.readAsBytesSync();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return _uint8list == null
        ? PressedOpacityButton(
            onPressed: () {
              loadingPDF();
            },
            child: Container(
              alignment: Alignment.center,
              child: CircularProgressIndicator(),
            ))
        : PdfPreview(
            build: _build,
            allowPrinting: false,
            allowSharing: false,
            canChangeOrientation: false,
            canChangePageFormat: false,
            useActions: false,
            dynamicLayout: true,
          );
  }

  FutureOr<Uint8List> _build(PdfPageFormat format) async {
    return _uint8list;
  }
}

class MyPdfDocumentParser extends PdfDocumentParserBase {
  final int size;

  MyPdfDocumentParser(Uint8List bytes, this.size) : super(bytes);

  @override
  void mergeDocument(PdfDocument pdfDocument) {}

  @override
  int get xrefOffset => 0;
}
